var jpress = require('jpress.js')

const Auth = {}
var app = getApp();

Auth.checkSession=function(appPage){
    let openId =wx.getStorageSync('openId');
    if(!openId){
        var userInfo = {
            avatarUrl:"../../images/gravatar.png",
            nickName:"登录",
            isLogin:false
        }
        appPage.setData({
            isLoginPopup: true,
            userInfo:userInfo
        });
    }
}

Auth.checkLogin=function(appPage){
    let wxLoginInfo =wx.getStorageSync('wxLoginInfo');
    wx.checkSession({
        success: function(){
            if(!wxLoginInfo.js_code){
                Auth.wxLogin().then(res=>{
                    appPage.setData({wxLoginInfo:res});
                    wx.setStorageSync('wxLoginInfo',res);
                    console.log('checkSession_success_wxLogins');
                })
            }
        },
        fail: function(){
            console.log("session_key 已经失效，需要重新执行登录流程");
            Auth.wxLogin().then(res=>{
                appPage.setData({
                    wxLoginInfo:res
                });
                wx.setStorageSync('wxLoginInfo',res);
                console.log('checkSession_fail_wxLoginfo');
            })
        }
    })
}

Auth.checkAgreeGetUser=function(e,app,appPage){
    let wxLoginInfo = wx.getStorageSync('wxLoginInfo');
    if(wxLoginInfo.js_code){
        Auth.agreeGetUser(e,wxLoginInfo).then(res=>{
            if (res.errcode==""){
                wx.setStorageSync('userInfo',res.userInfo);
                wx.setStorageSync('openId',res.openId);
                wx.setStorageSync('userLevel',res.userLevel);
                appPage.setData({openId:res.openId});
                appPage.setData({userInfo:res.userInfo});
                appPage.setData({userLevel:res.userLevel});
            }else{
                var userInfo ={avatarUrl:"../../images/gravatar.png",nickName:"点击登录",isLogin:false}
                appPage.setData({userInfo:userInfo});
                console.log("用户拒绝了授权");
            }
            appPage.setData({ isLoginPopup: false });
        })
    }else{
        console.log("登录失败");
        wx.showToast({
            title: '登录失败',
            mask: false,
            duration: 1000
        });
    }
}

// 同意或者取消
Auth.agreeGetUser=function(e,wxLoginInfo){
    return new Promise(function(resolve, reject) {
        let data={};
        data.js_code = wxLoginInfo.js_code;
        if(e.detail.errMsg=='getUserInfo:fail auth deny'){
            data.errcode = e.detail.errMsg;
            data.userInfo = {isLogin:false}
            data.userSession = "";
            resolve(data);
            return;
        }
        //未授权过,通过按钮授权
        var userInfoDetail = e.detail;

        if(userInfoDetail && userInfoDetail.userInfo){
            let userInfo =  userInfoDetail.userInfo;
            userInfo.isLogin =true;
            data.userInfo =userInfo;
            jpress.wxGetUserInfo(userInfoDetail,function (success,user) {
                if (success) {
                    //console.log(response.data.openId)
                    console.log("授权登录获取成功");
                    data.openId= user.wx_openid;
                    wx.setStorageSync('user',user);
                    var userLevel={};
                    if(user.userLevel){
                        userLevel=user.userLevel;
                    }else{
                        userLevel.level="0";
                        userLevel.levelName="订阅者";
                    }
                    data.userLevel=userLevel;
                    data.errcode="";
                    resolve(data);
                }else {
                    console.log("授权登录失败");
                }
            });
        }else{
            data.errcode="error";
            data.userInfo={isLogin:false};
            data.userSession="";
            resolve(data);
        }
    })
}

Auth.setUserInfoData = function(appPage){
    if(!appPage.data.openId){
          appPage.setData({
            userInfo: wx.getStorageSync('userInfo'),
            openId:wx.getStorageSync('openId'),
            userLevel:wx.getStorageSync('userLevel')
        })
    }else {
        console.log("appPage:" + appPage);
    }
}

// 微信登录，并获取sessionId
Auth.wxLogin=function(){
    return new Promise(function (resolve, reject) {
        wx.login({
            success: function (res) {
                let args = {};
                args.js_code = res.code;
                console.log("wxLogin code :"+ res.code)
                jpress.wxLogin(res.code);
                resolve(args);
            },
            fail: function (err) {
                console.log(err);
                reject(err);
            }
        });
    })
 }

Auth.logout=function(appPage){
    appPage.setData({
        openId:'',
        userLevel:{},
        userInfo:{},
        wxLoginInfo:{}
    })
    wx.removeStorageSync('userInfo');
    wx.removeStorageSync('openId');
    wx.removeStorageSync('userLevel');
    wx.removeStorageSync('wxLoginInfo');
}

Auth.userAuthorization = function () {
    var self = this;
    // 判断是否是第一次授权，非第一次授权且授权失败则进行提醒
    wx.getSetting({
        success: function success(res) {
            console.log(res.authSetting);
            var authSetting = res.authSetting;
            if (!('scope.userInfo' in authSetting)) {
                //if (util.isEmptyObject(authSetting)) {
                console.log('第一次授权');
                self.setData({ isLoginPopup: true })
            } else {
                console.log('不是第一次授权', authSetting);
                // 没有授权的提醒
                if (authSetting['scope.userInfo'] === false) {
                    wx.showModal({
                        title: '用户未授权',
                        content: '如需正常使用评论、点赞、赞赏等功能需授权获取用户信息。是否在授权管理中选中“用户信息”?',
                        showCancel: true,
                        cancelColor: '#296fd0',
                        confirmColor: '#296fd0',
                        confirmText: '设置权限',
                        success: function (res) {
                            if (res.confirm) {
                                console.log('用户点击确定')
                                wx.openSetting({
                                    success: function success(res) {
                                        console.log('打开设置', res.authSetting);
                                        var scopeUserInfo = res.authSetting["scope.userInfo"];
                                        if (scopeUserInfo) {
                                            self.getUsreInfo(null);
                                        }
                                    }
                                });
                            }
                        }
                    })
                }else {
                    auth.getUsreInfo(null);
                }
            }
        }
    });
}



module.exports = Auth;